import {
  api,
  util,
  storage
} from "../util";

import {
  router
} from '../router';
import {
  config
} from "./gloab";
import authorize from './authorize.js'
import { deepClone, isEmpty } from "../newUtil";
const app = getApp();

/**
 * 商品列表相关
 */
const list = {
  loadProductList(data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      ShowNoStock: data.isShowZeroStock,
      IsProduct: 1,
      storeisopenb2c: 1
    };
    if (data.sortField) {
      param.sortField = data.sortField
      param.sortDirect = data.sortDirect
      param.Orderby = "<" + data.sortField + ">" + data.sortDirect + "</" + data.sortField + ">"
    }
    if (entity != undefined && entity.fkId > 0) {
      param['UserId'] = entity.fkId;
      param['Token'] = entity.manager.Token;
    }
    if (data.rule_id != undefined && data.rule_id > 0) {
      param['ruleId'] = data.rule_id;
    }
    if (data.areaCode != undefined && data.areaCode != '') {
      param['AreaId'] = data.areaCode;
    }
    // 组装条件
    if (data.keywords.length > 0) {
      param['keywords'] = encodeURIComponent(data.keywords);
    }
    if (data.cid != undefined && data.cid > 0) {
      param['cid'] = data.cid;
    }
    if (data.ikcqr != undefined && data.ikcqr.length > 0) {
      param['ikcqr'] = data.ikcqr;
    }
    if (data.extattrs != undefined && data.extattrs.length > 0) {
      param['extattrs'] = data.extattrs;
    }
    var condition = "";
    if (data.bid != undefined && (data.bid.length > 0 || data.bid > 0)) {
      condition += "<BrandId>" + data.bid + "</BrandId>";
    }
    if (data.vid != undefined && (data.vid.length > 0 || data.vid > 0)) {
      condition += "<VendorIds>" + data.vid + "</VendorIds>";
    }
    if (data.minprice != undefined && data.minprice.length > 0) {
      condition += "<saleunitprice>" + data.minprice + "</saleunitprice>";
    }
    if (data.tag_id != undefined && data.tag_id > 0) {
      condition += "<TagId>" + data.tag_id + "</TagId>";
    }
    if (data.tag) {
      condition += "<TagId>" + data.tag + "</TagId>";
    }
    if (data.customAttrs) {
      condition += data.customAttrs;
    }
    if(data.minToPrice != ',' && data.minToPrice){
      condition += "<SaleUnitPrice>" + data.minToPrice + "</SaleUnitPrice>";
    }
    if(condition!=""){
      param['Condition'] = condition;
    }
    util.post("mall.product.page", param, function(res) {
      var isCache = res.isCache;
      res = res.data;
      if (res.Success) {
        let errorCount = 0 // 错误的商品数据
        res.Content.Data.map((item)=>{
          let units = item.AuxiliaryUnits
          if (units && units.length > 0) {
            for (let j = 0; j < units.length; j++) {
              if (item.CartCount > 0) {
                if (item.AuxUnit == units[j].Name) {
                  item.ZIndex = j
                  break
                }
              } else {
                if (item.DefaultUnit == units[j].Name) {
                  item.ZIndex = j
                  break
                }
              }
              if(!item.Qty){
                item.Qty = 0
              }
            }
          }
          if (isEmpty(item.ProductName) && isEmpty(item.SalesPrice) && isEmpty(item.Stock)) {
            errorCount += 1
          }
        });
        if (errorCount > 0) {
          util.setErrorLog(param, res)
        }
        if (callback != undefined && typeof(callback) == "function") {
          callback(res, isCache || false);
        }
      } else {
        util.alert(res.Message);
      }
    }, "3.0", null, false, data.PageIndex == 1 ? 2 : 0);
  },
  /**加载类目页筛选条件 */
  get_category_screens(data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      Token: entity.manager.Token,
      tid: data.typeId
    };
    if (data.keyword != undefined && data.keyword.length > 0) {
      param['Keyword'] = data.keyword;
    }
    util.post("mall.category.screen", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0");
  },
  /**加载商品目录 */
  loadCategoryinfo(CategoryId, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      Id: CategoryId
    };

    util.post("mall.category.info", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0", null, true, 1);
  },
  /**加载商品目录 */
  loadCategories(partId, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      UserId:entity.fkId,
      Condition: "<ParentId>" + partId + "</ParentId><IsUseCustom>false</IsUseCustom>",
      IsShowBrandAndAd: true,
      Token: entity.manager.Token
    };

    util.post("mall.category.tree", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.1", null, true);
  },
  loadChildCategory(parentId, callback) {
    var that = this;
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      UserId: entity.fkId,
      CategoryId: parentId || 0,
      Token: entity.manager.Token
    };

    util.post("mall.category.getCateDetails", param, function(res) {
      res = res.data;
      if (res.Success) {
        var content = res.Content;
        var cd = {
          bannerImage: content.AdvertisingImg || "",
          hasBanner: false,
          bannerLink: content.AdvertisingLink || "",
          categoryExtends: [],
        };

        if (Object.keys(content).length > 0) {
          content = content[0];

          if (cd.bannerImage != "")
            cd.hasBanner = true;
          var categoryHots = content.RecommCate || [];
          var categoryBrand = content.Brand || [];
          var categoryChildren = content.Category || [];
          var adver = {
            AdvertisingImg: content.AdvertisingImg,
            AdvertisingLink: content.AdvertisingLink
          };
          let list = []
          let second = []
          if (categoryHots.length > 0) {
            list.push({
              Name: "推荐分类",
              Source: categoryHots,
              Type: 2
            });
          }
          if (categoryChildren.length > 0) {
            let threeCategoryList = []
            let hasThreeCaregory = false // 是否存在三级目录
            categoryChildren.map((item, i) => {
              if (item.Children.length > 0) {
                hasThreeCaregory = true
              }
              threeCategoryList.push({
                Id: item.Id,
                Name: item.CateName,
                Source: item.Children,
                Type: 3,
                CateImg: item.CateImg ? item.CateImg : '',
                TypeId: item.TypeId
              })
              second.push(item)
            })
            if (!hasThreeCaregory) {
              list.push({
                Name: "二级分类",
                Source: second,
                Type: 2
              })
            } else {
              list = [...list, ...threeCategoryList]
            }
          }
          if (categoryBrand.length > 0)
            list.push({
              Name: "推荐品牌",
              Source: categoryBrand,
              Type: 1
            });
           
          // list.map((item)=>item.Source = that.newArrFn(item.Source));
          // console.log(status,'=======status',that.newArrFn(list));
          cd.categoryExtends = list.length == 0?list:that.newArrFn(list);
          cd.adver = adver;
        }
        if (callback != undefined && typeof(callback) == "function") {
          callback(cd);
        }
      }
    }, "3.1", null, true);
  },
  newArrFn(arr){
    if (!Array.isArray(arr)) {
      console.log('type error!')
      return
    }
    let res = [arr[0]];
    for (let i = 1; i < arr.length; i++) {
      let flag = true;
      for (let j = 0; j < res.length; j++) {
          if (arr[i].Name === res[j].Name) {
              flag = false;
              break
          }
      }
      if (flag) {
        res.push(arr[i])
      }
    }
    // console.log(res,'===========res');
    return res;
  },
  loadBrands(callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      Token:entity.manager.Token
    };

    util.post("mall.brand.getBrandList", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0", null, true, 1);
  },
  getWholesaleConfigs(fkid, fkflag, callback) {
    var that = this;
    config.getWholesaleConfigs(
      fkid,
      fkflag,
      'Wholesale',
      function(model) {       
        if (callback != undefined && typeof(callback) == "function") {
          callback(model);
        }
      }, true);
  },
  getAllPurchaseDroitByRole(callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      VisitorFlag: entity.fkFlag,
      VisitorId: entity.fkId,
      Token: entity.manager.Token,
    };

    util.post("core.droit.getallpurchasedroitbyrole", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0", null, true, 1);
  },
  getProductStockDistribution(args, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      ProductId: args.productId || 0,
      FKFlag: args.fkFlag || 2,
      FKId: args.fkId || 0,
      UserId: entity.fkId,
      Token: entity.manager.Token,
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      AreaId: 0
    };

    util.post("mall.goods.stockdistributionbyproductid", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.1", null, true, 1);
  },
  getGoodsStockDistribution(args, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      GoodsId: args.goodsId || 0,
      FKFlag: args.fkFlag || 2,
      FKId: args.fkId || 0,
      UserId: entity.fkId,
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      AreaId: 0,
      DepotId: -1
    };

    util.post("supplier.goodsstock.distribution", param, function (res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof (callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.1", null, true, 1);
  },
  /**
   * 通过ids获取商品列表数据（用于必买商品列表等页面）
   * @param {*} data 
   * @param {*} callback 
   */
  loadGoodsList(data, callback) {
    let entity = authorize.getEntity() || authorize.getDefault()
    let param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex || 1,
      PageSize: data.PageSize || 20,
      Status: 1,
      Shelved: 1, // 上架状态
    }
    let condition = ''
    if (entity != undefined && entity.fkId > 0) {
      condition += `<UserId>${entity.fkId}</UserId>`
      param['Token'] = entity.manager.Token
    }
    if (data.areaCode != undefined && data.areaCode != '') {
      condition += `<AreaId>${data.areaCode}</AreaId>`
    }
    if (!isEmpty(data.goodsIds)) {
      condition += `<goodsids>${data.goodsIds}</goodsids>`
    }
    // 组装条件
    if (!isEmpty(data.GoodsName)) {
      param['GoodsName'] = encodeURIComponent(data.GoodsName)
    }
    if (condition) {
      param['Condition'] = condition
    }
    util.post("mall.goods.page", param, function(res) {
      var isCache = res.isCache
      res = res.data
      if (res.Success) {
        res.Content.Data.map((item)=>{
          let units = item.AuxiliaryUnits
          if (units && units.length > 0) {
            for (let j = 0; j < units.length; j++) {
              if (item.CartCount > 0) {
                if (item.AuxUnit == units[j].Name) {
                  item.ZIndex = j
                  break
                }
              } else {
                if (item.DefaultUnit == units[j].Name) {
                  item.ZIndex = j
                  break
                }
              }
              if(!item.Qty){
                item.Qty = 0
              }
            }
          }
        })
        if (callback != undefined && typeof(callback) == "function") {
          callback(res, isCache || false)
        }
      } else {
        util.alert(res.Message)
      }
    }, "3.0", null, false, 0)
  },
}
/**商品详情相关 */
const detail = {
  /**获取商品即时信息 */
  loadProductInstantInfo(data, goodlist, productData, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    let goodsIds = [];
    if (goodlist) {
      goodlist.map((item) => {
        goodsIds.push(item.GoodsId);
      });
    }
    if (goodsIds.length == 0) {
      return;
    }
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProductId: data.productId,
      GoodsIds: goodsIds.join(","),
      Token: entity.manager.Token || '',
      UserId: entity.fkId,
      AreaId: data.areaCode
    };
    data.goodsIds = goodsIds;
    if (data.discountType == 2 && data.discountId > 0) {
      param["DiscountType"] = data.discountType;
      param["DiscountId"] = data.discountId;
    }
    util.post("mall.product.instantinfo", param, function(res) {
      res = res.data;
      if (res.Success) {
        let goods = res.Content.Goods || [];
        goods.map((g,index) => {
          g.Translated = g.Radix || 1;
          g.DefaultUnit = g.Unit;
          //设置下拉默认选择项
          // let units = goodlist[index].AuxiliaryUnits;
          let units = g.AuxiliaryUnits;
          if (units.length > 0) {
            for (let j = 0; j < units.length; j++) {
              if (g.AuxUnit == units[j].Name) {
                g.ZIndex = j;
                g.DefaultUnit = units[j].Name;
                break;
              }
            }
          }
          for (let k = 0; k < goodlist.length; k++) {
            if (g.GoodsId == goodlist[k].GoodsId) {
              g.FKId = goodlist[k].SupplierId;
              g.BarCode = goodlist[k].BarCode;
              g.GoodsCode = goodlist[k].GoodsCode;
              g.SpecValue = goodlist[k].SpecValue;
              g.DefaultPic = goodlist[k].DefaultPic;
              break;
            }
          }
          g.ProductName = productData.ProductName;
          g.ZeroStockBuy = productData.EnableZeroStockBuy;
          g.SBuyUpperLimit = g.BuyUpperLimit || 0;
          g.SBuyLowerLimit = g.BuyLowerLimit || 0;
          g.SStock = g.Stock;
          g.Translated = g.AuxRate || 1;
          g.CartCount = g.AuxQty;
          g.IsDeduction = productData.IsDeduction;
          g.DeductRate = productData.DeductRate;
          g.SaleMode = productData.SaleMode;
          // g.AuxiliaryUnits = goodlist[index].AuxiliaryUnits;
          g.ShowPrice = res.Content.ShowPrice;
          g.Status = productData.Status;
          detail.getFastUnitPrice(g, g.CartCount, g.Translated == 1);
        })
        productData.Price = res.Content.MinPrice;
        productData.MaxSalesIntegral = res.Content.MaxSalesIntegral;
        productData.MaxSalesPrice = res.Content.MaxSalesPrice;
        productData.MinSalesIntegral = res.Content.MinSalesIntegral;
        productData.MinSalesPrice = res.Content.MinSalesPrice;
        productData.BuyPower = res.Content.BuyPower;
        productData.FavoriteId = res.Content.FavoriteId;
        productData.StockText = res.Content.StockText;
        if(!productData.isPanic){
          productData.Stock = res.Content.Stock;
        }
        productData.ShowPrice = res.Content.ShowPrice;
        productData.MinPrice = res.Content.MinPrice;
        productData.allUnit = res.Content.DefaultUnit;
        if (callback != undefined && typeof(callback) == "function") {
          callback(goods, res);
        }
      }
    }, "3.0",null,false);
  },
  
  /**加载商品规格等信息 */
  loadSpecific(data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      Token: entity.manager.Token,
      UserId: entity.fkId,
      ProductId: data.productId,
      IsTransfer: data.spectStyle == 1 || false,
      AreaId: data.areaCode
      //isShelved: 1,
    };
    if (data.discountType == 2 && data.discountId > 0) {
      param["DiscountType"] = data.discountType;
      param["DiscountId"] = data.discountId;
    }
    util.post("mall.goods.getfrontgoods", param, function(res) {
      res = res.data;
      if (res.Success) {
        let goods = res.Content.Goods || [],
        units=res.Content.Units || [],
        specifictions = res.Content.Specifiction || [];
        let PanicBuy = res.Content.PanicBuy || []
        let hasPanicData = false // 是否已有特价的数据，当为优惠券商品时，商品本身没有特价信息，需要重新设置
        goods.map((g) => {
          //这里需要把原始值用另一个字段存下来，方便后面计算时用原始值计算
          g.SBuyLowerLimit = g.BuyLowerLimit || 0;
          g.SBuyUpperLimit = g.BuyUpperLimit || 0;
          g.SStock = g.Stock;
          g.Translated = g.Radix;
          g.ShowPrice = res.Content.ShowPrice;
          //设置下拉默认选择项
          if (units && units.length > 0) {
            for (let j = 0; j < units.length; j++) {
              if (g.DefaultUnit == units[j].Name) {
                g.ZIndex = j;
                break;
              }
            }
          }
          detail.getFastUnitPrice(g, g.CartCount, g.Translated == 1);
          detail.decoratePromotion(g, data.promotions);
          if (g.isPanic || g.PanicGoods) {
            hasPanicData = true
          }
        })
        if (!hasPanicData) {
          // 重新将特价信息写入商品中
          for (let i = 0; i < PanicBuy.length; i++) {
            let p = PanicBuy[i] || []
            if (!isEmpty(p)) {
              detail.decorate_specific(goods, p.PanicGoods, 3)
            }
          }
        }
        if (specifictions){
          specifictions.map((item) => {
            let spectArray = item.SpecValue;
            item.GoodsIds = [];
            item.MarkSrc=[];
            for (let k = 0; k < spectArray.length; k++) {
              item.MarkSrc.push({MarkSrc:spectArray[k].MarkSrc,name:spectArray[k].Value});
              // console.log(item.MarkSrc,'=============fgfhgh');
              if (spectArray[k].Checked) {
                item.GoodsIds = spectArray[k].GoodsIds.split(",");
              }
            }
          });
        }
        if (callback != undefined && typeof(callback) == "function") {
          callback(goods, specifictions, units, res.Content);
        }
      } else {
        util.tips(res.Message);
      }
    }, "3.0",null,false);
  },
  decoratePromotion(g, promotions) {
    if (promotions && promotions.length > 0) {
      var market = [];
      promotions.map((item, i) => {
        if (item.goodsIds=="0"){
          item.goodsArray = item.productIds.split(",");
          if (item.goodsArray.indexOf(g.ProductId + "") > -1) {
            market.push(item);
          }
        }
        else{
          item.goodsArray = item.goodsIds.split(",");
          if (item.goodsArray.indexOf(g.GoodsId+"") > -1) {
            market.push(item);
          }
        }
      });
      g.market = market;
    }
  },
  /**获得快速下单的单位价格 */
  getFastUnitPrice(g, num, isBaseUnit = false) {
    var t = detail.parseRule(g.UnitPrices, g.Translated, num, isBaseUnit);
    if (t.has) {
      g.SalesPrice = t.price;
      g.SalesIntegral = t.integral;
      g.Price = t.MarketPrice;
    }
  },
  /**
   * 解析阶梯规则
   * isBaseUnit:是否是商品，默认是货品
   */
  parseRule: function(unitPrices, translated, num,isBaseUnit=false) {
    var isbreak = false;
    var t = {
      price: 0,
      integral: 0,
      has: false
    };
    if (unitPrices == undefined) return t;
    var rule = unitPrices[translated] ? unitPrices[translated] : Object.values(unitPrices)[0];
    if (!rule) return t;
    // 未登录时，num可能会在某些地方传入undefined
    if (isEmpty(num)) {
      num = 0
    }
    // if (isBaseUnit&&num == 0) {
    //   let item = rule[rule.length - 1];
    //   t.price = item.Price;
    //   t.integral = item.Integral;
    //   t.has = true;
    //   return t;
    // }
    rule.map(function(item,index) {
      // if (t.has) return;
      if(num == 0){
        if (index == 0) {
          t.originalPrice = item.CostPrice||item.Price;
          t.MarketPrice = item.MarketPrice;
          t.price = item.Price;
          t.integral = item.Integral;
          t.has = true;
        } else {
          if (t.price > item.Price) {
            t.price = item.Price;
            t.originalPrice = item.CostPrice||item.Price;
            t.MarketPrice = item.MarketPrice;
            t.integral = item.Integral;
            t.has = true;
          }
          if (t.price == item.Price && t.integral > item.Integral) {
            t.integral = item.Integral;
            t.has = true;
          }
        }
      }else{
        if (item.MinQuantity == 1 && num < item.MinQuantity) {
          num = item.MinQuantity
        }
        if ((item.MinQuantity - 1) < num && (item.MaxQuantity >= num || item.MaxQuantity == 0)) {
          t.originalPrice = item.CostPrice||item.Price;
          t.price = item.Price;
          t.MarketPrice = item.MarketPrice;
          t.integral = item.Integral;
          t.has = true;
          // return;
        }
      }
    });
    return t;
  },
  /**
   * 装饰多规格
   */
  decorate_specific: (specific_goods, panicGoods, ispanic) => {
    if (!ispanic) return;
    var panicGoods = panicGoods || [];
    if (panicGoods.length > 0) {
      for (var i = 0; i < specific_goods.length; i++) {
        for (var j = 0; j < panicGoods.length; j++) {
          var p = panicGoods[j];
          var g = specific_goods[i];
          if (g.GoodsId == p.GoodsId) {
            g.MinQuantity = p.MinQuantity; //限购的最小数量
            g.MaxQuantity = p.MaxQuantity;
            // g.originalPrice = g.UnitPrices[0].Price;
            var quantity = p.Quantity; //活动数量
            quantity = isNaN(quantity) || quantity == undefined ? 0 : quantity;
            var buyQuantity = p.BuyQuantity; //已购数量
            buyQuantity = isNaN(buyQuantity) || buyQuantity == undefined ? 0 : buyQuantity;
            var stock = util.calulateReduce(quantity,buyQuantity); //库存 limit
            //允许0库存，显示可用活动数量；不允许0库存，显示库存、活动可以数量的小值
            if(g.ZeroStockBuy == 0){ 
              stock = stock > g.SStock ? g.SStock : stock;
            }
            g.originalProductData = deepClone(g)
            g.SStock = stock;
            g.SaleMode = 0;
            g.PriceType = 0;
            g.BuyLowerLimit = p.MinQuantity || 0;
            g.BuyUpperLimit = p.MaxQuantity > 0 && p.MaxQuantity <= stock ? p.MaxQuantity : stock;
            g.SBuyLowerLimit = g.BuyLowerLimit || 0;
            g.SBuyUpperLimit = g.BuyUpperLimit || 0;
            g.DiscountId = p.PanicId;
            g.DiscountType = 2;
            g.isPanic = true;
            //特价的单位价格
            g.UnitPrices = p.UnitPrices;
            g.StockText = `${g.SStock}${g.Unit}`;
            //绑定特价信息
            g.PanicGoods = panicGoods;
            //特价
            let price_obj = detail.parseRule(g.UnitPrices, g.Translated, g.AuxQty);
            if (price_obj.has) {
              g.SalesPrice = price_obj.price;
              g.SalesIntegral = price_obj.integral;
              g.originalPrice = price_obj.originalPrice;
              g.MarketPrice =  price_obj.MarketPrice;
              specific_goods[i] = g;
            }
          }
        }
      }
    }
  },
  /**加载商品详情 */
  loadProductDetail(ptype, data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    switch (parseInt(ptype)) {
      case 0:
        this.loadCommonProduct(data, entity, callback);
        break;
      case 3:
        this.loadCommonProduct(data, entity, callback);
        break;
      case 1:
        this.loadGroupProduct(data, 1, entity, callback);
        break;
      case 2:
        this.loadGroupProduct(data, 2, entity, callback);
        break;
    }
  },
  /**加载普通商品详情 */
  loadCommonProduct(data, entity, callback) {
    entity = entity || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProductId: data.pid,
      UserId: entity.fkId
    };
    util.post("mall.product.baseinfo", param, function(res) {
      res = res.data;
      if(res.Success){
        let specifictions = res.Content.Specifictions || []
        specifictions.map((item) => {
          let spectArray = item.SpecValue;
          item.GoodsIds = [];
          item.MarkSrc = [];
          for (let k = 0; k < spectArray.length; k++) {
            item.MarkSrc.push({MarkSrc:spectArray[k].MarkSrc,name:spectArray[k].Value});
            if (spectArray[k].Checked) {
              item.GoodsIds = spectArray[k].GoodsIds.split(",");
            }
          }
        });
        if (callback != undefined && typeof(callback) == "function") {
          callback(res);
        }
      }else{
        util.tips(res.Message);
        setTimeout(()=>{
          router.navigateBack();
        },2000);
      }
    }, "3.1",null,false);
  },
  /**加载限时特价商品详情 */
  loadPanicProduct(discountId,ProductId, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      DiscountId: discountId,
      Token:entity.manager.Token,
      ProductId:ProductId
    };
    util.post("market.panicbuy.detail", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data.Content);
      }
    },"3.1",null,false);
  },

  /**加载拼团预售商品详情 */
  loadGroupProduct(data, flag, entity, callback) {
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      FKWay: app.dns.fkWay,
      Flag: flag,
      ItemId: data.ItemId,
      Id: data.Id,
      UserId: entity.fkId
    };
    util.post("market.groupbuy.detail", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    },"3.0",null,false);
  },

  /**商品拼团和预售的货品规格列表 */
  loadGroupGoods(groupId, flag, callback) {
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      FKWay: app.dns.fkWay,
      GroupType: 1,
      Flag: flag,
      GroupId: groupId
    };
    util.post("market.groupbuy.getgoods", param, function(res) {
      res = res.data;

      if (callback != undefined && typeof(callback) == "function") {
        callback(res.Content);
      }
    },"3.0",null,false);
  },
  /**获取拼团预售货品规格 */
  loadGroupSpecGoods(data, callback) {
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      FKWay: app.dns.FKWay,
      GroupId: data.GroupId,
      GroupType: data.GroupType,
      Flag: data.Flag
    };
    util.post("market.groupbuy.getgoods", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data.Content);
      }
    },"3.0",null,false);
  },
  /**换算批发规则 */
  loadUnitContext(units, baseUnit) {
    if (units.length <= 0) return "";
    var productUnitText = "";
    for (var i = 0; i < units.length; i++) {
      var u = units[i];
      if (u.Id > 0) {
        productUnitText += '1{1}={0}{2} '.format(u.Translated, u.Name, baseUnit);
      }
    }
    return productUnitText;
  },
  /**随机获取商品列表 猜你喜欢 */
  loadProductsByRandom(data, pid, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize:data.PageSize,
      fields: "ProductId,ProductName,SalesPrice,SalesIntegral,DefaultPic,FkId,IsDeduction,DeductRate,SaleMode,Sells",
      pid: pid,
      storeId: entity.fkId
    };
    util.post("mall.product.listbyrandom", param, function(res) {
      res = res.data;
      if (res.Success) {
        res.Content.map(function(item) {
          item.Price = item.SalesPrice;
        });
      }
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.Content);
      }
    }, "3.0",null,false);
  },
  /**商品扩展信息 */
  loadProductRelate(pid, callback) {
    var entity = authorize.getEntity();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      pid: pid
    };
    util.post("mall.product.relate", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0",null,false);
  },
  getStockByArea(data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    let goodsIds = [];
    if (data.goodlist) {
      data.goodlist.map((item) => {
        goodsIds.push(item.GoodsId);
      });
    }
    if (goodsIds.length == 0) {
      return;
    }
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      Token: entity.manager.Token,
      AreaId: data.code,
      ProductId: data.productId,
      GoodsIds: goodsIds
    };
    util.post("mall.goods.getstockbyarea", param, function(res) {
      res = res.data;
      if (res.Success) {
        let goods=res.Content;
        for(let index=0;index<goods.length;index++){         
          if (data.goodlist[index].isPanic==true) continue;
          if(data.goodlist[index].GoodsId == goods[index].GoodsId){
            data.goodlist[index].Stock = goods[index].Stock;
            data.goodlist[index].StockText = goods[index].StockText;
          }
        };
        if (callback != undefined && typeof(callback) == "function") {
          callback(data.goodlist);
        }
      }
    }, "3.0", null, true, 1);
  },
}

/**商品类公用方法 */
const mall = {
  /**
   * 加载收藏商品列表
   */
  load_favorite_list(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      FKId: entity.fkId,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      Keywords: data.keywords,
      Condition: `<AreaId>${data.areaCode}</AreaId>`,
    };
    util.post("mall.product.favorite", param, function(res) {
      res = res.data;
      if (res.Success) {
        if (callback != undefined && typeof(callback) == "function") {
          callback(res.Content);
        }
      }
    }, "3.0", null, false, 0);
  },
  /**
   * 加载常购商品
   *  */
  load_offen_buy_list(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      FKId: entity.fkId,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      Keywords: data.keywords,
      Condition: `<AreaId>${data.areaCode}</AreaId>`,
      Orderby: data.sortField + data.sortDirect
    };
    util.post("order.trade.oftenbuyproducts", param, function(res) {
      res = res.data;
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.Content);
      }
    }, "3.0", null, false, 0);
  },
  /**添加收藏 */
  addFavorite(data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: 2,
      FKId: data.ProductFKId,
      ProductFKId: data.ProductFKId,
      ProductId: data.ProductId,
      token: entity.manager.Token
    };
    util.post("mall.favorite.add", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, false);
  },
  /**取消收藏 */
  delFavorite(id, callback) {
    var entity = authorize.getEntity();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor == 2 ? "Supplier" : "Store",
      FKId: app.dns.proprietorId,
      id: id,
      token: entity.manager.Token
    };
    util.post("mall.favorite.del", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, false);
  },
  /**
   * 根据编码获取商品信息
   */
  get_product_info_by_code: (code, areaCode, callback) => {
    var entity = authorize.getEntity();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      LoginFlag: entity.fkFlag,
      Token: entity.manager.Token,
      BuyerId: entity.fkId,
      Barcode: code,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      AreaId: areaCode
    };
    util.post("mall.product.listbybarcode", param, function(res) {
      res = res.data;
      if (res.Success) {
        res.Content.map((item)=>{
          item.Goods.map((g) => {
            g.Name = g.ProductName;
            g.CartCount = g.AuxQty;
            //这里需要把原始值用另一个字段存下来，方便后面计算时用原始值计算
            g.SBuyLowerLimit = g.BuyLowerLimit || 0;
            g.SBuyUpperLimit = g.BuyUpperLimit || 0;
            g.SStock = g.Stock;
            g.Translated = g.Radix;
            g.ShowPrice = item.ShowPrice;
            let unit_index = 0;
            for (let k = 0; k < g.AuxiliaryUnits.length; k++) {
              if (g.AuxiliaryUnits[k].Translated == g.Translated) {
                unit_index = k;
                break;
              }
            }
            g.ZIndex = unit_index;
            item.CartCount = g.CartCount;
            detail.getFastUnitPrice(g, g.CartCount, g.Translated==1);
          });
          if (item.Specifiction){
            item.Specifiction.map((item) => {
              let spectArray = item.SpecValue;
              item.GoodsIds = [];
              item.MarkSrc = [];
              for (let k = 0; k < spectArray.length; k++) {
                item.MarkSrc.push({MarkSrc:spectArray[k].MarkSrc,name:spectArray[k].Value});
                if (spectArray[k].Checked) {
                  item.GoodsIds = spectArray[k].GoodsIds.split(",");
                }
              }
            });
          }
        })
      
      }
      if (callback != undefined && typeof(callback) == "function") {
        callback(res);
      }
    }, "3.0", null, false);
  },
  /**
   * 判断输入框有效值
   * @goods 货品
   * @current_unit 当前单位
   * @q 数量
   */
  judge_input_validate: (goods, translated, q, quantityDigits, callback) => {
    var data = {
      translated: translated,
      rule: goods.PriceRule || goods.PriceRules,
      priceType: goods.PriceType
    };
    //是否允许零库存购买
    data.zerostockbuy = parseInt(goods.ZeroStockBuy == undefined || goods.ZeroStockBuy == "" ? "0" : goods.ZeroStockBuy);

    //限时特价时，0库存下单失效；
    if (goods.discountId > 0) {
      data.zerostockbuy = 0;
    }
    if (translated != 1) {
      quantityDigits = 0;
    }
    //购买下限
    data.stock_lower_limit = goods.BuyLowerLimit;
    //购买上限
    data.stock_upper_limit = data.zerostockbuy > 0 ? 999999 : (goods.Stock < goods.BuyUpperLimit ? goods.Stock : (goods.BuyUpperLimit == 0 ? 999999 : goods.BuyUpperLimit));
    //起批数
    if (quantityDigits == 0) {
      data.min = Math.ceil(data.stock_lower_limit / data.translated);
      //判断最大值
      data.max = Math.floor(data.stock_upper_limit / data.translated);
    } else {
      data.min = (data.stock_lower_limit / data.translated).toFixed(quantityDigits);
      //判断最大值
      data.max = (data.stock_upper_limit / data.translated).toFixed(quantityDigits);
    }
    //判断最低购买数量
    if (q > 0 && q < data.min) {
      goods.CartCount = data.min;
      util.tips("最低购买数量为" + data.min + (goods.DefaultUnit || goods.Unit), "提示");
      if (callback != undefined && typeof(callback) == "function") {
        goods.CartCount = data.min;
        callback(goods);
      }
      return false;
    }
    //判断最大购买数量
    if (q > 0 && q > data.max) {
      goods.CartCount = data.max;
      util.tips("最大购买数量为" + data.max + (goods.DefaultUnit || goods.Unit), "提示");
      if (callback != undefined && typeof(callback) == "function") {
        goods.CartCount = data.max;
        callback(goods);
      }
      return false;
    }

    if (callback != undefined && typeof(callback) == "function") {
      goods.CartCount = q;
      if (goods.isPanic == true) {
        callback(goods);
        return true;
      }
      callback(goods);
    }
    return true;
  }
}
/**缺货登记相关方法 */
const scant = {
  /**提交缺货登记 */
  saveScanty(data, callback) {
    var entity = authorize.getEntity()|| authorize.getDefault();
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProprietorId: app.dns.proprietorId,
      Proprietor: app.dns.proprietor,
      FKWay: app.dns.fkWay,
      ToFKId: entity.fkId,
      Token: entity.manager.Token,
      ProductId: data.ProductId,
      GoodsId: data.GoodsId,
      ProductName: data.ProductName,
      BrandId: data.BrandId,
      Mobile: data.Mobile,
      Quantity:data.Quantity,
      Unit: data.Unit
      // VerifyCode: data.VerifyCode,
      // CodeToken: data.CodeToken
    };
    util.post("mall.goods.scanty", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, false);
  },
  getScantyPhone(callback){
    var entity = authorize.getEntity()|| authorize.getDefault();
    var param = {
      userId:entity.fkId
    };
    util.post("mall.scanty.getusermobile", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, false);
  },
  /**缺货登记列表 */
  loadScantyList(data, callback) {
    var entity = authorize.getEntity()|| authorize.getDefault();
    var param = {
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      sortField: data.sortField,
      sortDirect: data.sortDirect,
      ToFKFlag: entity.fkFlag,
      ToFKId: entity.fkId,
      Token: entity.manager.Token,
      FKWay: app.dns.fkWay,
    };
    var condition = "";
    if (data.keywords.length > 0) {
      condition += "<KeyWords>"+data.keywords+"</KeyWords>";
    }
    if (data.startTime.length > 0) {
      condition += "<StartAddTime>"+data.startTime+"</StartAddTime>";
    }
    if (data.endTime.length > 0) {
      condition += "<EndAddTime>"+data.endTime+"</EndAddTime>";
    }
    if (data.showInStock >= 0) {
      condition += "<ShowInStock>"+data.showInStock+"</ShowInStock>";
    }
    if (condition.length > 0) {
      param.Condition = condition;
    }
    util.post("mall.scanty.page", param, function(res) {
      var result = "{\"count\":0,\"data\": []}";
      res = res.data
      if (res.Success) {
        result = res.Content;
      }
      if (callback != undefined && typeof(callback) == "function") {
        callback(result);
      }
    }, "3.0");
  },
  /**删除缺货登记记录 */
  removeScanty(data, callback) {
    var entity = authorize.getEntity();
    var param = {
      scantyId: data.scantyId,
      ProprietorId: app.dns.proprietorId,
      Token: entity.manager.Token
    };
    util.post("mall.scanty.remove", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  }
}

const comments = {
  getWaitCommentOrderInfo(oddNumber, callback) {
    var entity = authorize.getEntity();
    var param = {
      OddNumber: oddNumber,
      Token: entity.manager.Token
    };
    util.post("mall.comments.getwaitcommentorderinfo", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, false);
  },
  /**
   * 提交评论
   */
  submitComments(orderinfo, callback) {
    var str = "";
    for (var i = 0; i < orderinfo.Items.length; i++) {
      var item = orderinfo.Items[i];
      item.Score = item.Score || 5;
      if (item.Score == 0) {
        util.tips("请为商品打分");
        return;
      }
      var commentImages = "";
      if (item.VirtualPaths && item.VirtualPaths.length > 0) {
        commentImages += "<CommentImages>";

        for (var j = 0; j < item.VirtualPaths.length; j++) {
          var imgsrc = item.VirtualPaths[j];
          commentImages += `<CommentImage><VirtualPath><![CDATA[${imgsrc}]]></VirtualPath><Reorder>${j}</Reorder></CommentImage>`;
        }
        commentImages += "</CommentImages>";
      }
      str += `
      <Comment>
          <FKFlag>${item.FKFlag}</FKFlag>
          <FKId>${item.FKId}</FKId>
          <OrderId>${item.OrderId}</OrderId>
          <ProductId>${item.ProductId}</ProductId>
          <GoodsId>${item.GoodsId}</GoodsId>
          <Score>${item.Score}</Score>
          <Content><![CDATA[${item.Content||""}]]></Content>
          ${commentImages}
      </Comment>
      `
    }
    var entity = authorize.getEntity();
    var param = {
      ProprietorId: app.dns.proprietorId,
      Token: entity.manager.Token,
      FKFlag: orderinfo.FKFlag,
      FKId: orderinfo.FKId,
      OrderId: orderinfo.Id,
      OrderNumber:orderinfo.OddNumber,
      Comments: str,
      AttitudeScore: orderinfo.AttitudeScore || 5,
      LogisticsScore: orderinfo.LogisticsScore || 5,
      IsAnonymous: orderinfo.IsAnonymous
    }
    util.post("mall.comments.saveorderproductscomments", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0", null, true);
  },
  loadList: function(condition, data, callback) {
    var entity = authorize.getEntity();
    var param = {
      FKFlag: condition.fkFlag,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      SortField: data.sortField,
      SortDirect: data.sortDirect,
      Token: entity.manager.Token,
      IsComment: condition.state
    };
    util.post("mall.mycomment.page", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data.Content);
      }
    }, "3.0");
  },
  /**
   * 获得评论详情
   */
  getDetail: function(condition, callback) {
    var entity = authorize.getEntity();
    var param = {
      Id: condition.id,
      FKFlag: condition.fkFlag,
      ProprietorId: app.dns.proprietorId,
      Token: entity.manager.Token
    };
    util.post("mall.comments.detail", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data.Content);
      }
    }, "3.0");
  },
  getCommentsInfo(condition, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Gid: condition.gid,
      Pid: condition.pid,
      FKId: condition.fkId,
      FKFlag: condition.fkFlag,
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      Token: entity.manager.Token
    };
    util.post("mall.comments.get", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  },
  /**
   * 获得某个商品的评论列表
   */
  getProductCommentList(condition, data, callback) {
    var entity = authorize.getEntity() || authorize.getDefault();
    //var orderby = '<' + data.sortField + ">" + data.sortDirect + '</' + data.sortField + ">";
    var param = {
      ProductId: condition.pid,
      ListType: condition.listType,
      FKId: condition.fkId,
      FKFlag: condition.fkFlag,
      ProprietorId: app.dns.proprietorId,
      PageIndex: data.PageIndex,
      PageSize: data.PageSize,
      // Orderby: orderby,
      Token: entity.manager.Token
    };
    util.post("mall.comments.frontpage", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data.Content);
      }
    }, "3.0");
  },
  /**
   * 获得店铺评价信息
   */
  getSupplierCommentInfo(condition, callback) {
    var entity = authorize.getEntity();
    var param = {
      Gid: condition.gid,
      Pid: condition.pid,
      FKId: condition.fkId,
      FKFlag: condition.fkFlag
    };
    util.post("supplier.comments.score", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  },
  /**
   * 互动社区--列表
  */
  getCommunityList(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      PageIndex:data.PageIndex,
      PageSize:data.PageSize,
      Token:entity.manager.Token,
      // Type:data.Type,
      FKId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      Content:data.keyword
    };
    if(data.SectionId != 0){
      param.SectionId=data.SectionId
    }
    util.post("market.interaction.list", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  },
  //获取互动版块列表
  getNavList(callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Token:entity.manager.Token,
      Proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId
    };
    util.post("market.interaction.section.get", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  },
  // 获取用户发现页，统计数
  getUserFind(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var proprietorId = '';
    var FKFlag = '';
    var FKId = '';
    var UserId = '';
    // if(data.ProprietorId){ proprietorId = data.ProprietorId;}else{proprietorId = app.dns.proprietorId;}
    if(data.FKFlag){FKFlag = data.FKFlag;}else{ FKFlag = entity.fkFlag;}
    if(data.FKId){FKId = data.FKId;}else{ FKId = entity != undefined ? entity.fkId : 0 ;}
    if(data.ManagerId){ UserId = data.ManagerId;}else{UserId = entity.manager.ManagerId;}
    var param = {
      Proprietor:app.dns.proprietor,
      proprietorId:app.dns.proprietorId,
      FKFlag:FKFlag,
      FKId:FKId,
      UserId:UserId,
      Token:entity.manager.Token,
    }; 
    util.post("market.interaction.user.statistics", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  },
  // 获取指定帖子详情
  getPostDetail(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    // ,ProprietorId:app.dns.proprietorId,Proprietor:app.dns.proprietor,FKId:entity != undefined ? entity.fkId : 0 ,FKFlag:app.dns.proprietor
    var param = {Token:entity.manager.Token,Id:data.Id};
    util.post("market.interaction.detail", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") { 
        callback(res.data);
      }
      // if (res.Success) {
      //   if (callback != undefined && typeof (callback) == "function") {
      //     callback(res.data);
      //   }
      // }else{
      //   util.tips(res.Message);
      // }
    }, "3.0");
  },
  //获取指定帖子评论列表
  getPostCommentList(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor:app.dns.proprietor,
      ProprietorId:app.dns.proprietorId,
      InteractionId:data.InteractionId,
      Token:entity.manager.Token
    };
    util.post("market.interaction.detail.comment", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  },
  //累加帖子浏览量
  getPostViews(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      InteractionId:data.InteractionId,
      Token:entity.manager.Token
    };
    util.post("market.interaction.changebrowse",param,function(res){
      callback(res.data);
    },"3.0")
  },
  // 分页获取发现页帖子列表
  getFoundPostList(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor:app.dns.proprietor,
      ProprietorId:data.ProprietorId?data.ProprietorId:app.dns.proprietorId,
      FKFlag:data.FKFlag?data.FKFlag:entity.fkFlag,
      FKId:data.FKId?data.FKId:entity.fkId,
      UserId:data.UserId?data.UserId:entity.manager.ManagerId,
      Flag:data.Flag,
      Token:entity.manager.Token,
      PageIndex:data.PageIndex,
      PageSize:data.PageSize
    };
    util.post("market.interaction.assign.list",param,function(res){
      callback(res.data);
    },"3.0")
  },

  //互动模块添加回复
  getAddReply(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param ={
      ProprietorId:app.dns.proprietorId,
      Token:entity.manager.Token,
      InteractionId:data.InteractionId,
      CommentId:data.CommentId,
      ParentId:data.ParentId,
      Content:data.Content
    }
    util.post("market.interaction.reply.add",param,function(res){
      callback(res.data);
    },"3.0")
  },
  //分页获取指定评论下的回复列表
  getCommentList:function(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {InteractionId:data.InteractionId,CommentId:data.CommentId,Token:entity.manager.Token, ProprietorId: app.dns.proprietorId};
    util.post("market.interaction.replay.list",param,function(res){
      callback(res.data);
    },"3.0")
  },
  //添加帖子评论
  getAddComment(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {Token:entity.manager.Token,Content:data.Content,InteractionId:data.InteractionId, ProprietorId: app.dns.proprietorId};
    util.post("market.interaction.comment.add",param,function(res){
      callback(res.data);
    },"3.0")
  },
  //删除帖子
  getDelPost(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {Token:entity.manager.Token,Id:data.Id, ProprietorId: app.dns.proprietorId};
    util.post("market.interaction.delete", param, function(res) { 
      callback(res.data);
    }, "3.0");
  },
  //互动模块删除回复
  getReplyDel(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {ProprietorId:app.dns.proprietorId,Token:entity.manager.Token,Id:data.Id, ProprietorId: app.dns.proprietorId};
    util.post("market.interaction.reply.delete",param,function(res){
      callback(res.data);
    },"3.0")
  },
  //删除指定评论记录
  getCommentRecord(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {ProprietorId:app.dns.proprietorId,Token:entity.manager.Token,CommentId:data.CommentId, ProprietorId: app.dns.proprietorId};
    util.post("market.interaction.comment.delete",param,function(res){
      callback(res.data);
    },"3.0")
  },
  //用户对指定用户,进行关注
  getUserFollowAdd(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Token:entity.manager.Token,
      FollowFkFlag:data.FollowFkFlag,
      FollowFkId:data.FollowFkId,
      FollowManagerId:data.FollowManagerId,
      ProprietorId: app.dns.proprietorId
    };
    util.post("market.interaction.follow.add", param, function(res) {
      callback(res.data);
    }, "3.0");
  },
  //用户对指定用户,进行取消关注
  getUserCancelFollow(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Token:entity.manager.Token,
      FollowFkFlag:data.FollowFkFlag,
      FollowFkId:data.FollowFkId,
      FollowManagerId:data.FollowManagerId,
      ProprietorId: app.dns.proprietorId
    };
    util.post("market.interaction.follow.cancel",param,function(res) {
      callback(res.data);
    }, "3.0");
  },
  // 根据指定人，获取其关注他人列表 -- 接口通的，数据是空的[]
  getFollowList(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {
      Proprietor:data.Proprietor != 'undefined' ? data.Proprietor:app.dns.proprietor,
      ProprietorId:data.ProprietorId != 'undefined' ? data.ProprietorId:app.dns.proprietorId,
      FKFlag:data.FKFlag != 'undefined' ? data.FKFlag:app.dns.proprietorId,
      FKId:data.FKId != 'undefined' ? data.FKId:entity.fkId,
      UserId:data.UserId != 'undefined' ? data.UserId:entity.manager.ManagerId,
      UserName:data.UserName != 'undefined' ?data.UserName:app.dns.proprietorId,
      PageIndex:data.PageIndex,
      PageSize:data.PageSize
    };
    var link = "market.interaction.follow.page";
    if(data.statusId == 0){ // 关注
      link = "market.interaction.follow.page";
    }else if(data.statusId == 1){ //粉丝
      link = "market.interaction.fans.page";
    }
    util.post(link, param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  },
  // 用户对互动帖子、评论点赞 -- 加一了，状态没有返还
  getUserFollow(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {Token:entity.manager.Token,Id:data.Id,Type:data.Type, ProprietorId: app.dns.proprietorId};
    util.post("market.interaction.favorite.add", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  },
  //用户对互动帖子、评论点赞,进行取消
  getUserCancel(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {Token:entity.manager.Token,Id:data.Id,Type:data.Type, ProprietorId: app.dns.proprietorId};
    util.post("market.interaction.favorite.delete", param, function(res) {
      if (callback != undefined && typeof(callback) == "function") {
        callback(res.data);
      }
    }, "3.0");
  },
  
  // 发布图文等
  getBindPost(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var img = data.Image.join(',');
    var goods = data.goods;
    var items = [];
    var item = [];
    if(goods.length > 0){
      for(var i = 0 ;i<goods.length;i++){
        items.push(goods[i].SaleValue);
      }
    } 
    item =`<InteractionSales><Item><SaleType>1</SaleType><SaleValue>${items}</SaleValue><Reorder>1</Reorder><Status>1</Status></Item></InteractionSales>`;
    var str = `<root> <action>insert</action><Type>${data.Type}</Type><Title><![CDATA[${data.Title}]]></Title><Image>${img}</Image><Video>${data.Video}</Video><Offcial>0</Offcial><OnTop>0</OnTop><Content><![CDATA[${data.Content}]]></Content><LinkSrc><![CDATA[${data.LinkSrc}]]></LinkSrc><LinkName><![CDATA[${data.LinkName}]]></LinkName><SectionId>${data.SectionId}</SectionId>${item}<InteractionScope><RelateType>${data.RelateType}</RelateType><ScopeType>${data.ScopeType}</ScopeType><ScopeValue>${data.ScopeValue}</ScopeValue><Status>1</Status></InteractionScope></root>`;
    var param = {
      Proprietor: app.dns.proprietor,
      ProprietorId: app.dns.proprietorId,
      FKFlag: app.dns.proprietor,
      FKId: app.dns.proprietorId,
      Interaction:str,
      Token:entity.manager.Token
    };
    // console.log(param,'----param',str);
    // return;
    util.post("market.interaction.save",param,function(res){
      callback(res.data);
    },"3.0")
  },
  //获取已删除帖子详情
  getDelPostDetail(data,callback){
    var entity = authorize.getEntity() || authorize.getDefault();
    var param = {Token:entity?entity.manager.Token:'',Id:data.Id, ProprietorId: app.dns.proprietorId};
    util.post("market.interaction.getdel",param,function(res){
      callback(res.data);
    },"3.0")
  },
  //通过优惠套餐ID获取套餐明细
  getPackageDetail(data,callback){ 
    var entity = authorize.getEntity();
    var param = {Token:entity?entity.manager.Token:'',PackedSaleId:data.PackedSaleId,Proprietor: app.dns.proprietor,ProprietorId: app.dns.proprietorId};
    util.post("market.packedsaleproduct.widget",param,function(res){
      callback(res.data)
    },"3.0")
  },
  // 通过商品ID获取所有关联优惠套餐明细
  getSaleDetail(data,callback){
    var entity = authorize.getEntity();
    var param = {Token:entity?entity.manager.Token:'',ProductId:data.ProductId,Proprietor: app.dns.proprietor,ProprietorId: app.dns.proprietorId};
    util.post("market.packedsaleproduct.detail",param,function(res){
      callback(res.data)
    },"3.0")
  },
  //资料列表(在发现展示)
  getListFormoment(data,callback){
    var entity = authorize.getEntity() || {};
    let manager = entity.manager || {};
    let userId = 0
    if (entity) {
      userId = entity.fkId || 0
    }
    var param = {
      Token: manager.Token || '',
      userId: userId,
      ParentId:data.ParentId,
      keyword:data.keyword,
      ManagerId:manager.ManagerId,
      ForderId: data.ParentId,
      ProprietorId: app.dns.proprietorId
    };
    util.post("oa.docment.getlistformoment",param,function(res){
      callback(res.data.Content)
    },"3.0")
  },
  getPackageList(data,callback){
    var entity = authorize.getEntity();
    var param = {Token:entity?entity.manager.Token:'',StoreId:entity.fkId,Proprietor: app.dns.proprietor,ProprietorId: app.dns.proprietorId,PageIndex:data.PageIndex,PageSize:data.PageSize,Status:data.Status,Condition:"<Keywords><![CDATA[" + (data.keywords) + "]]></Keywords>"};
    util.post("market.packedsale.page",param,function(res){
      callback(res.data)
    },'3.1')
  },
}
/**规格选择事件 */
class specModel {
  /**
   * 点规格事件
   */
  static onSpectEvent(event, data, callback) {
    let {
      spect_name_index,
      spect_value_index
    } = event;
    let {
      specifictions,
      selectSpectValues,
      goodSpecific,
      goodsIndex
    } = data;
    let spectValuesObj = specifictions[spect_name_index].SpecValue,
      spectValueObj = null;
    for (let i = 0; i < spectValuesObj.length; i++) {
      if (i == spect_value_index) {
        //如果是灰色的
        if (spectValuesObj[i].Status == -1) {
          return;
        }
        // goodsIndex = spect_value_index;
        spectValuesObj[i].Checked = !spectValuesObj[i].Checked;
        spectValueObj = spectValuesObj[i].Checked ? spectValuesObj[i] : null;
        
      } else {
        spectValuesObj[i].Checked = false;
      }
    }
    if (spectValueObj != null) {
      specifictions[spect_name_index].GoodsIds = spectValueObj.GoodsIds.split(",");
      this.checkedSpecValueEvent(specifictions, specifictions[spect_name_index]);
    } else {
      specifictions[spect_name_index].GoodsIds = [];
      this.checkedSpecValueEvent(specifictions);
    }
    this.setGoodsIndex(specifictions, goodSpecific, goodsIndex, callback);
  }
  /**
   * 获得goodsId
   */
  static getGoodsIds(intersection) {
    let valueIds = null;
    let goodsIndex = -1;
    intersection.map((sf, i) => {
      if (sf.GoodsIds.length > 0) {
        if (valueIds == null) {
          valueIds = sf.GoodsIds;
        } else {
          valueIds = sf.GoodsIds.filter(function(item) {
            return valueIds.indexOf(item) > -1;
          });
        }
      }
    });
    return valueIds;
  }
  /**
   * 设置索引
   */
  static setGoodsIndex(specifictions, goodSpecific, preIndex, callback) {
    let intersection = specifictions.filter(item => item.GoodsIds.length > 0);
    let valueIds = this.getGoodsIds(intersection);
    let goodsIndex = -1;
    if (valueIds != null && valueIds.length > 0) {
      for (let i = 0; i < goodSpecific.length; i++) {
        if (goodSpecific[i].GoodsId == valueIds[0]) {
          if (specifictions.length == intersection.length) {
            goodsIndex = i;
          }
        } else {
          detail.getFastUnitPrice(goodSpecific[i], goodSpecific[i].CartCount, goodSpecific[i].Translated == 1);
        }
      }
    }else if (specifictions.length == 0) {
      //如果没有规格默认第一个
      goodsIndex = 0;
    }
    if (callback && typeof(callback) == "function") {
      callback({
        specifictions: specifictions,
        goodSpecific: goodSpecific,
        currentIndex: goodsIndex,
        goodsIndex: goodsIndex
      });
    }

  }
  static getUnion(current) {
    var tempArr = [];
    current.SpecValue.map(function(sp) {
      if (tempArr.length == 0) {
        tempArr = sp.GoodsIds.split(",");
      } else {
        tempArr = tempArr.concat(sp.GoodsIds.split(","));
      }
    });
    return tempArr;
  }
//   static getOccur(arrs){
//     if (arrs.length ==1) {
//         return arrs[0].split(',')
//     }
//     let arr = arrs[0].split(',');
//     for (let i = arrs.length; i--;) {
//         let p = { "boolean": {}, "number": {}, "string": {} };
//         let obj = [] ;
//         arr = arr.concat(arrs[i].split(',')).filter((x) => {
//             let t = typeof x;
//             return !((t in p) ? !p[t][x] && (p[t][x] = 1) : obj.indexOf(x) < 0 && obj.push(x));
//         });
//         if (!arr.length) return [];
//     }
//     return arr;
// }
  /**选中时触发事件 */
  static checkedSpecValueEvent(specifictions, current) {
    //置为可用状态
    specifictions.map((sf, i) => {
      sf.imgList=[];
      sf.SpecValue.map((sp, j) => {
        sf.imgList.push(sp.ImagePath);
        sp.Status = 1;
      });
    });
    //未选中规格与选中规格比较
    specifictions.map((sfRow, i2) => {
      sfRow.SpecValue.map((spRow, j) => { 
        //当前行中未选中的规格
         if(!spRow.Checked){
            let currentGoodsId=spRow.GoodsIds.split(",");
            //选中行，且不等于当前行
            let selectRow=specifictions.filter(item => item.SpecId!=sfRow.SpecId);
            //循环选中行
            selectRow.map((sr, i2) => {
              //循环选中规格
              sr.SpecValue.map((srs)=>{
                if(srs.Checked){
                  let goodsIds=srs.GoodsIds.split(',');
                  currentGoodsId=currentGoodsId.filter((item)=>{return goodsIds.indexOf(item)>-1});
                }
              })
            });
            if(currentGoodsId==null||currentGoodsId.length==0){
              spRow.Status=-1
            }
         }
      });
    });


  }

}
module.exports = {
  list,
  detail,
  mall,
  scant,
  comments,
  specModel
}